import os
from text_util import *
from file_util import *
import random

def display_options(data):
    print("该程序具有的功能：")
    for index, (key, value) in enumerate(data.items(), start=1):
        print(f"{index}: {value['description']}")

def display_words(word_list):
    # 按字母顺序排序
    sorted_words = sorted(word_list)
    
    # 去掉文件名的后缀并展示给用户
    for i, word in enumerate(sorted_words, start=1):
        # 去掉文件名的后缀
        word_without_extension = os.path.splitext(word)[0]
        print(f"{i}. {word_without_extension}")

def select_words(word_list, user_input):
    try:
        # 根据用户输入的数字选择单词
        selected_indices = [int(idx) - 1 for idx in user_input.split() if idx.strip().isdigit()]
        selected_words = [os.path.splitext(word_list[idx])[0] for idx in selected_indices]
        
        # 如果选择的单词数为0或者选择的索引超出了列表的范围，我们需要捕获这种情况
        if not selected_words or any(idx >= len(word_list) for idx in selected_indices):
            raise IndexError
    except (ValueError, IndexError):
        # If user input is incorrect or empty, select all words or a random subset
        max_num = 10
        if len(word_list) > max_num:
            print_red(f"输入无效或超出范围。随机选择{max_num}个单词。")
            selected_words = random.sample([os.path.splitext(word)[0] for word in word_list], max_num)
        else:
            print_red("输入无效或超出范围。选择全部单词。")
            selected_words = [os.path.splitext(word)[0] for word in word_list]
    return selected_words

def process_word_category(word_path, message_list, delimiter, total_len, is_multi_line):
    user_input = get_user_input(is_multi_line)
    user_input = user_input.strip(' ')
    file_path = os.path.join(word_path, f'{user_input.lower()}.md')

    if os.path.exists(file_path):
        print_red(f"单词 {user_input} 已存在!")

    user_input_dic = content2dic(role="user", content=user_input, delimiter=delimiter)
    assistant_content = generate_assistant_content(message_list, user_input_dic, total_len=total_len)

    formatted_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S" + f"\n")
    save_content_to_file(file_path, formatted_time + f"\n")

    save_content_to_file(file_path, assistant_content)
    save_content_to_file(file_path, f"\n\n\n")
    
    print_red(f'内容已成功保存到文件: {file_path}')

def process_story_category(story_path, word_files, message_list, delimiter, total_len, is_multi_line):
    print("=================================================")
    if not word_files:
        print("文件夹中没有单词文件。")
        result_string = " "
    else:
        display_words(word_files)
        print("请输入数字选择单词（用空格分隔）:")
        user_input = get_user_input(is_multi_line=is_multi_line)
        selected_words = select_words(word_files, user_input)
        result_string = ", ".join(selected_words)
        print(f"你选择的单词是: {result_string}")

    user_input = result_string

    user_input_dic = content2dic(role="user", content=user_input, delimiter=delimiter)
    assistant_content = generate_assistant_content(message_list, user_input_dic, total_len=total_len)

    file_path = write_time_to_file(file_path=story_path)
    save_content_to_file(file_path, f"user: \n\n" + user_input + f"\n\n")
    save_content_to_file(file_path, f"assistant: \n\n" + assistant_content + f"\n\n\n\n")
    
    print_red(f'内容已成功保存到文件: {file_path}')
    print()

def process_other_category(folder_path, message_list, delimiter, total_len, is_multi_line):
    user_input = get_user_input(is_multi_line)

    user_input_dic = content2dic(role="user", content=user_input, delimiter=delimiter)
    assistant_content = generate_assistant_content(message_list, user_input_dic, total_len=total_len)

    # Modify this part based on how you want to handle other categories
    file_path = write_time_to_file(file_path=folder_path)
    save_content_to_file(file_path, f"user: \n\n" + user_input + f"\n\n")
    save_content_to_file(file_path, f"assistant: \n\n" + assistant_content + f"\n\n\n\n")

    print_red(f'内容已成功保存到文件: {folder_path}')
    print()

